home *** CD-ROM | disk | FTP | other *** search
Text File | 1989-04-27 | 2.2 KB | 76 lines | [TEXT/????] |
- ;;; $Header: r-rat.scm,v 1.3 88/02/10 00:25:25 GMT gjs Exp $
- ;;;; RATIONALIZE, HEURISTIC-ROUNDER
-
- (if-mit (declare (usual-integrations)))
-
- ;;; This file defines RATIONALIZE (Rrrrs) and uses it to make a heuristic
- ;;; number rounder.
-
- (define rationalize-wallp false)
-
- (define (rationalize x . optionals)
- (define *default-maxden* 6e23)
- (let ((epsilon
- (if (not (null? optionals)) (car optionals) (* 10 *machine-epsilon*)))
- (maxden
- (if (and (not (null? optionals))
- (not (null? (cdr optionals))))
- (cadr optionals)
- *default-maxden*)))
- (define (rat1 x)
- (let ((ix (truncate x)))
- (let loop ((num ix) (den 1) (onum 1) (oden 0) (xx x) (a ix))
- (if rationalize-wallp
- (pp `((num= ,num) (den= ,den) (xx= ,xx))))
- (cond ((> den maxden) false)
- ((and (not (= den 0))
- (< (abs (/ (- x (/ num den)) x))
- epsilon))
- (cons num den))
- (else
- (let* ((y (/ 1 (- xx a)))
- (iy (truncate y)))
- (loop (+ (* iy num) onum)
- (+ (* iy den) oden)
- num
- den
- y
- iy)))))))
- (cond ((integer? x) x)
- ((real? x)
- (cond ((< (abs x) epsilon)
- 0)
- ((< x 0)
- (let ((a (rat1 (abs x))))
- (if a
- (cons (- (car a)) (cdr a))
- a)))
- (else (rat1 x))))
- (else
- (error "Can't rationalize" x)))))
-
- ;;; Some processes, such as finding the roots of a polynomial, can
- ;;; benefit by heuristic rounding of results (to a nearby rational).
-
- ;;; Heuristic rounding will occur to a rational within
- (define heuristic-rounding-tolerance 1.0e-9)
- ;;; that is expressible with a denominator less than the
- (define heuristic-rounding-denominator 100)
- ;;; if such a rational exists.
-
- (define (heuristic-round-real x)
- (let ((r (rationalize x
- heuristic-rounding-tolerance
- heuristic-rounding-denominator)))
- (if r
- (if (real? r)
- r
- (make-rational (car r) (cdr r)))
- x)))
-
- (define (heuristic-round-complex z)
- (if (real? z)
- (heuristic-round-real z)
- (make-rectangular (heuristic-round-real (real-part z))
- (heuristic-round-real (imag-part z)))))
-